import React, { useState, useEffect } from 'react'
import apiService from '../utils/api.js'

/**
 * 添加到歌单模态框组件
 * @component
 * @param {Object} props - 组件属性
 * @param {boolean} props.visible - 控制模态框显示/隐藏
 * @param {Function} props.onClose - 关闭模态框的回调函数
 * @param {Function} props.onAddSuccess - 添加成功后的回调函数
 * @param {Object} props.selectedSong - 当前选中的歌曲对象
 * @returns {JSX.Element} 添加到歌单模态框组件
 */
function AddToPlaylistModal({ visible, onClose, onAddSuccess, selectedSong }) {
  const [userPlaylists, setUserPlaylists] = useState([])
  const [loading, setLoading] = useState(false)

  // 当模态框显示且有选中歌曲时，获取用户歌单
  useEffect(() => {
    if (visible && selectedSong) {
      fetchUserPlaylists()
    }
  }, [visible, selectedSong])

  // 获取用户歌单
  const fetchUserPlaylists = async () => {
    try {
      setLoading(true)
      const currentUser = apiService.getCurrentUser()
      const userId = currentUser?.id
      const response = await apiService.getUserPlaylists({ userId })
      if (response.code === 200) {
        setUserPlaylists(response.data || [])
      } else {
        // 使用模拟数据作为备选
        setUserPlaylists([
          { id: 1, name: '我喜欢的音乐' },
          { id: 2, name: '跑步专属' },
          { id: 3, name: '工作学习' }
        ])
      }
    } catch (err) {
      console.error('获取用户歌单失败:', err)
      // 使用模拟数据作为备选
      setUserPlaylists([
        { id: 1, name: '我喜欢的音乐' },
        { id: 2, name: '跑步专属' },
        { id: 3, name: '工作学习' }
      ])
    } finally {
      setLoading(false)
    }
  }

  // 添加歌曲到歌单
  const addSongToUserPlaylist = async (playlistId) => {
    if (!selectedSong || !playlistId) return
    
    try {
      setLoading(true)
      const response = await apiService.addSongToPlaylist(playlistId, selectedSong.id)
      if (response.code === 200) {
        alert('添加到歌单成功！')
        // 调用添加成功回调
        if (onAddSuccess) {
          onAddSuccess()
        }
        // 关闭模态框
        onClose()
      } else {
        alert('添加到歌单失败: ' + (response.error || response.message || '未知错误'))
      }
    } catch (err) {
      console.error('添加歌曲到歌单失败:', err)
      alert(err.message || '网络错误，无法添加到歌单')
    } finally {
      setLoading(false)
    }
  }

  // 如果模态框不可见，则不渲染任何内容
  if (!visible) {
    return null
  }

  return (
    <div className="song-form-modal">
      <div className="song-form">
        <div className="modal-header">
          <h3>添加到歌单</h3>
          <button 
            className="close-btn" 
            onClick={onClose}
            disabled={loading}
          >
            ×
          </button>
        </div>
        <div className="add-to-playlist-content">
          <p>选择要添加的歌单：</p>
          <div className="playlist-selection">
            {loading ? (
              // 加载状态显示
              <div className="loading">加载歌单中...</div>
            ) : userPlaylists.length > 0 ? (
              // 显示歌单列表
              userPlaylists.map(playlist => (
                <button 
                  key={playlist.id}
                  className="playlist-option"
                  onClick={() => addSongToUserPlaylist(playlist.id)}
                  disabled={loading}
                >
                  {playlist.name}
                </button>
              ))
            ) : (
              // 无歌单状态显示
              <div className="empty-state">
                <p>暂无可用歌单</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default AddToPlaylistModal